var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var ejs = require('ejs');
const proxy = require('http-proxy-middleware'); //引入代理中间件
var index = require('./routes/index');
var users = require('./routes/users');

var app = express();

if (process.env.NODE_ENV === 'dev') {
  var webpack = require("webpack");
  var webpackDevMiddleware = require('webpack-dev-middleware'),
    webpackHotMiddleware = require('webpack-hot-middleware'),
    webpackDevConfig = require('./webpack.config.dev');

  var compiler = webpack(webpackDevConfig);

  app.use(webpackDevMiddleware(compiler, {

    // public path should be the same with webpack config
    publicPath: webpackDevConfig.output.publicPath,
    noInfo: true,
    stats: {
      colors: true
    }
  }));
  app.use(webpackHotMiddleware(compiler));
}


// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'html');
app.engine('html', ejs.renderFile);

// uncomment after placing your favicon in /public
app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
  extended: false
}));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

const apiProxy = proxy('/mmbiz.qpic.cn', {
  target: 'http://mmbiz.qpic.cn',
  changeOrigin: true,
  pathRewrite: {
    '^/mmbiz.qpic.cn': ''
  },
  onProxyReq(proxyReq, req, res) {
    // proxyReq.setHeader('Host', 'mmbiz.qpic.cn');
    // proxyReq.setHeader('Referer', 'http://mmbiz.qpic.cn')
    // proxyReq.setHeader('Origin', 'http://mmbiz.qpic.cn');
    console.log(proxyReq)
  },
  headers: {
    'Origin': 'http://mmbiz.qpic.cn',
    'Referer': 'http://mmbiz.qpic.cn',
    "Host": "mmbiz.qpic.cn"
  }
}); //将服务器代理到localhost:8080端口上[本地服务器为localhost:3000]
app.use('/mmbiz.qpic.cn', apiProxy);

app.use('/api', users);
app.use('*', index);

// catch 404 and forward to error handler
app.use(function (req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handler
app.use(function (err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;
